interface Result{
    set: (key: string, value: any, shelfTime?: number) => void,
    get: (key: string) => unknown,
    remove: (key: string) => void,
    clear: (exclude?: string[]) => void
}

/**
 * @returns { set, get, remove, clear }
 */
export function useLocalStorage(): Result{

    const storage = sessionStorage

    const remove = (key: string) => storage.removeItem(key)

    /**
     * 设置存储
     * @param key key
     * @param value 值
     * @param shelfTime 可选，有效期（单位：ms）
     */
    const set = (key: string, value: any, shelfTime?: number) => {
        storage.setItem(key, JSON.stringify({
            lastTime: shelfTime ? new Date().getTime() + shelfTime : undefined,
            value
        }))
    }

    /**
     * 获取存储值
     * @param key key
     * @returns undefined | any
     */
    const get = (key: string) => {

        const { lastTime, value } = JSON.parse(storage.getItem(key) || '{}')

        if(!lastTime || lastTime > new Date().getTime() ) return value
        else  remove(key)
        
        return undefined 
    }

    /**
     * 获取过去时间
     * @param key key
     * @returns number | undefined
     */
    const getLastTime = (key: string) => {
        const { lastTime } = JSON.parse(storage.getItem(key) || '{}')
        return lastTime
    }

    /**
     * 清除所有存储值
     * @param exclude 可选，不需要清除的keys
     */
    const clear = (exclude?: string[]) => {
        const _lastTimes: any = {}
        const _catch: any = {}

        exclude?.forEach((key: string) => {
            _catch[key] = get(key)
            _lastTimes[key] = getLastTime(key)
        })

        storage.clear()

        exclude?.forEach((key: string) => {
            set(key, _catch[key], _lastTimes[key])
        })
    }

    return {
        set, 
        get, 
        remove, 
        clear
    }
}